<template>
	<view class="order-wrapper">
		<u-sticky bgColor="#fff">
			<u-tabs  lineColor="#F33C72" :list="tabList" :current="currentTabs" :scrollable="false" @click="changeTab"></u-tabs>
		</u-sticky>
		<view class="order-list">
			<view class="order-item" v-for="item in orderList" :key="item.orderId">
				<view class="store-msg">
					<view class="flex-c-s">
						<view class="flex-c" style="align-items: center;">
							<image class="store-icon"  src="/static/images/store-b.png" mode=""></image>
							<view>{{item.store.storeName}}</view>
							<uni-icons type="forward" color="#999" size="20"></uni-icons>
						</view>
						<view>
							<!-- 1、待付款 2、付款中 3、款失败 4、付款完成 5、待退款 6、款中7、退款完成 -->
							<uni-tag v-if="item.status === 1" :text="ReservationEnum[item.status]" custom-style="background-color: #FF6F99; border-color: #FF6F99; color: #fff;"></uni-tag>
							<uni-tag v-if="item.status === 2" :text="ReservationEnum[item.status]" custom-style="background-color: #FFC75B; border-color: #FFC75B; color: #fff;"></uni-tag>
							<uni-tag v-if="item.status === 4" :text="ReservationEnum[item.status]" custom-style="background-color: #F33C72; border-color: #F33C72; color: #fff;"></uni-tag>
							<uni-tag v-if="item.status === 3" :text="ReservationEnum[item.status]" custom-style="background-color: #22D49D; border-color: #22D49D; color: #fff;"></uni-tag>
							
						</view>
					</view>
				</view>
				<view class="goods-wrapper" @click="reservationInfo(item.id)">
					<view class="goods-item flex-c-s" >
						<view class="flex-c">
							<image class="goods-pic"  :src="item.product?.listImage" mode="aspectFill"></image>
						</view>
						<view class="goods-msg">
							<view class="goods-top ">
								<view class="goods-title" style="display: flex; flex-direction: column;">
									<view>{{ item.product?.productDetail.name }}</view>
								</view>
								<view class="goods-price">
									<view class="flex-c-s">￥{{ item.product?.productDetail.sellingPrice }}</view>
									<view class="color999 fz26">
										已售{{ item.product?.productDetail.sold }}件
									</view>
									<!-- <view style="color: #999999;">共{{ item.productQuantity }}件</view> -->
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="order-msg flex-c">
					<view>
						{{ item.createdAt }}
					</view>
					<view class="price">
						<view>实付款￥</view><view class="priceNum">{{ item.price }}</view>
					</view>
				</view>
				
				<view class="flex-c-s" style="padding-top: 30rpx;">
					<view class="flex-c">
						<text class="fz26 color666" style="margin-right: 20rpx;">{{item.status === 3 ? '押金状态' : ''}}</text> 
						<view class="flex-c" v-if="item.status === 3">
							<u-tag v-if="item.depositStatus === 2" borderColor="#999" bgColor="#999" :text="depositStatusText[item.depositStatus]" ></u-tag>
							<u-tag v-if="item.depositStatus === 4" :text="depositStatusText[item.depositStatus]" type="warning"></u-tag>
							<u-tag v-if="item.depositStatus === 3" :text="depositStatusText[item.depositStatus]" type="success"></u-tag>
							<u-tag v-if="item.depositStatus === 5" :text="depositStatusText[item.depositStatus]" type="success"></u-tag>
							<u-tag v-if="item.depositStatus === 1" :text="`${depositStatusText[item.depositStatus]} ￥${item.depositPrice}`" type="error"></u-tag>
							<u-tag v-if="item.depositStatus === 6" :text="depositStatusText[item.depositStatus]" type="error"></u-tag>
						</view>
					</view>
					<view class="order-menu flex-c">
						<!-- <view class="shouhou order-status-btn">申请售后</view> -->
						<!-- <view class="wuliu">查看物流</view> -->
						<!-- <view v-if="item.status === 1" class="fukuan order-status-btn" @click="reservationHandle(item.id)">立即预约</view> -->
						<!-- <view v-if="item.status === 1" class="fukuan order-status-btn" @click="refundMoneyHandle(item.id)">退押金</view> -->
						<!-- <view v-if="item.status === 3 && item.depositStatus === 1" class="shouhuo order-status-btn" @click="paymentDepositHandle(item.id)">支付押金</view> -->
					
						<u-tag :plain="true" shape="circle" v-if="item.status === 1" borderColor="#EB5883" bgColor="#EB5883" color="#fff" text="立即预约" @click="reservationHandle(item.id)"></u-tag>
						<u-tag :plain="true" shape="circle" v-if="item.status === 3 && (item.depositStatus === 1 || item.depositStatus === 2)" borderColor="#EB5883" bgColor="#EB5883" color="#fff" text="支付押金" @click="paymentDepositHandle(item.id)"></u-tag>
						<u-tag :plain="true" shape="circle" v-if="item.depositStatus === 3" borderColor="#EB5883" bgColor="#EB5883" color="#fff" text="退押金" @click="refundMoneyHandle(item.id)"></u-tag>
					</view>
				</view>
				
				<view class="flex-c-s" v-if="item.depositStatus === 3" style="margin-top: 24rpx;">
					<text class="fz26 color666">锁密码</text>
					<text class="fz26">{{item.store.lockPassword}}</text>
				</view>
			</view>
			<view class="no-data" v-if="!orderList.length">
				<NoData />
			</view>
			<u-loadmore v-show="orderList.length" :status="statusText" marginTop="20" :loading-text="loadingText"
			        :loadmore-text="loadmoreText"  :nomore-text="nomoreText" line />
		</view>
		
		<u-popup :show="showPopup" mode="bottom" :round="15" @close="close">
			<view class="reservation-info-content fz30">
				<view class="reservation-form-item flex-c-s">
					<text class="reservation-form-item-label">备注信息</text>
					<input v-model="remark" placeholder="输入预约备注信息" style="background-color: #f5f5f5; flex: 1; height: 40rpx; padding: 10rpx 20rpx; font-size: 30rpx;" />
				</view>
				<view class="reservation-form-item flex-c-s">
					<text class="reservation-form-item-label">预约时间</text>
					<text class="color-theme" @click="selectTime">{{ date ? date : '选择时间'}}</text>
				</view>
				
				<button class="public-large-btn" @click="submitReservation">提交预约</button>
			</view>
		</u-popup>
		
		<view class="">
			<u-datetime-picker title="选择时间" :show="showDate" v-model="time" mode="datetime" @confirm="confirm" @cancel="cancel"></u-datetime-picker>
		</view>
		
		<Payment ref="paymentNode" :disabledWeChatPay="true" @confirm="confirmHandle" @changeType="changeType" />
		<CustomeModal ref="customeModalNode" @confirmModal="confirmModal" />
		<CustomeModal ref="tryCustomeModalNode" @confirmModal="tryConfirmModal" content="正在尝试余额支付" />
	</view>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, computed, ref } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { reservationList, reservationUse, paymentDeposit, refundMoney } from '@/http/my'
import { ReservationEnum, depositStatusText, payType } from '@/config' 
import { getOrderTime } from '@/utils/tools'

import NoData from '@/components/NoData.vue'
import Payment from '@/components/Payment.vue'
import CustomeModal from '@/components/CustomeModal.vue'

import type { IOrder } from '@/types'

export default defineComponent({
	components: { NoData, Payment, CustomeModal },
	setup() {
		const paymentNode = ref()
		const customeModalNode = ref()
		const tryCustomeModalNode = ref()
		const state = reactive({
			tabList: [
				{ name: '待使用', id: 1}, 
				{ name: '预约中', id: 4 }, 
				{ name: '预约成功', id: 3 },
				{ name: '已完成', id: 2 },
			],
			pageSize: 10,
			page: 1,
			total: 0,
			status: 1,
			orderStatus:0,
			orderList:[] as Array<IOrder>,
			showPopup: false,
			showDate: false,
			remark: '',
			time: 0,
			date: '',
			goodsId: -1,
			payType: 2,
			ReservationEnum,
			depositStatusText,
			loadingText: '努力加载中',
			loadmoreText: '轻轻上拉',
			nomoreText: '没有更多了',
			currentTabs: 0,
		})
		
		onLoad( async () => {
			uni.hideLoading()
			orderListFun()
		})
		
		const orderListFun = async () => {
			uni.showLoading({ title: '加载中' })
			let pramas = {
				page: state.page,
				pageSize: state.pageSize,
				status: state.status, 
			}
			console.log(pramas);
			try{
				let res = await reservationList(pramas) 
				if(res.code === 0) {
					state.orderList = [...state.orderList,...(res.data?.list || [])] 
					state.total = res.data?.total
				} else {
					uni.showToast({
						title: res.msg || '请求出错了',
						icon: 'none'
					})
				}   
				console.log(res);
			}catch(e){ 
			}
			uni.hideLoading()
		}
		
		const changeTab = (item: {name: string, id: number, index: number}) => {
			state.orderList = []
			state.page = 1
			state.status = item.id
			orderListFun() 
		}
		
		onReachBottom(() => { // 页面触底事件
			if(state.total === 0) return;
			if(state.total === state.orderList.length) return;
			state.page ++
			orderListFun()  
		})
		
		// const goToOrderDetails = (item: IOrder) =>{
		// 	console.log(item);
		// 	uni.navigateTo({
		// 		url:`/pages/myPackge/order/details?id=${item.Id}`
		// 	})
		// }
		
		const statusText = computed(() => {
			return state.total === state.orderList.length ? 'nomore' : 'loadmore'
		})
		
		const reservationHandle = async (id: number) => {
			state.showPopup = true
			state.goodsId = id
			
		}
		
		const selectTime = () => {
			state.time = new Date().getTime()
			state.showDate = true
		}
		
		const confirm = (e: {value: number}) => { 
			state.date = getOrderTime(false, e.value) 
			state.showDate = false
		}
		
		const cancel = () => state.showDate = false;
		
		const submitReservation = async () => {
			if(!state.date) {
				uni.showToast({
					title: '请选择预约时间',
					icon: 'none'
				})
				return 
			}
			
			let curTime = new Date();
			let target = new Date(curTime.setMinutes(curTime.getMinutes() + 30));
			if(new Date(state.date).getTime() < new Date(target.getTime()).getTime()) { 
				uni.showToast({
					title: '预约时间不能小于当前时间',
					icon: 'none'
				})
				return 
			} 
			let p = {appointmentRemark: state.remark, appointmentTime: state.date, id: state.goodsId}
			console.log(p);
			let res = await reservationUse(p)
			
			if(res.code === 0) {
				state.page = 1
				state.orderList = []
				state.currentTabs = 1
				state.status = 4
				
				state.showPopup = false
				state.date = ''
				orderListFun()  
				uni.showToast({
					title: '预约成功之后提示等待客服联系',
					icon: 'none',
				})
				
			} else {
				uni.showToast({
					title: '预约失败',
					icon: 'error'
				})
			} 
		}
		
		const paymentDepositHandle = async (id: number) => { // 支付押金
			state.goodsId = id
			paymentNode.value.openLayer()
		}
		
		const refundMoneyHandle = async (id: number) => { // 退押金
			let res = await refundMoney(id)  
			if(res.code === 0) {
				uni.showToast({
					title: '申请成功',
					icon: 'success'
				})
				state.page = 1
				state.orderList = []
				orderListFun() 
			} else {
				uni.showToast({
					title: '申请失败',
					icon: 'error'
				})
			}
		}
		
		const changeType = (type: number) => { // 切换支付类型
			state.payType = type
		}
		
		const confirmHandle = async (type: number,) => { // 确定支付回调
			state.payType = type
			console.log(state.payType);
			if(state.payType === 3 || state.payType === 4) {
				customeModalNode.value.showModal()
			} else if(state.payType === 2){
				let res = await paymentDeposit({id: state.goodsId, payType: 2, payPassword: ''})
				if(res.code === 0) {
					uni.requestPayment({
						provider: 'alipay',
						orderInfo: res.data.payParam, 
						success: function (res) {
							state.page = 1
							state.orderList = []
							orderListFun() 
							uni.showToast({ title: '支付成功', icon: 'success' })
							
						},
						fail: function (err) { 
							customeModalNode.value.cancel()
							tryCustomeModalNode.value.showModal()
						}
					})
				}
			}
			
		}
		const close = () => {
			state.remark = ''
			state.date = ''
			state.showPopup = false
		}
		
		const reservationInfo = (id: number) => {
			uni.navigateTo({
				url: `/pages/myPackge/reservation/reservationInfo?id=${id}`
			})
		}
		
		const tryConfirmModal = async (content: string) => {
			if(content) {
				confirmModal(content, 4)
			} else {
				uni.showToast({ title: '输入支付密码', icon: 'error' }) 
			}
			
		}
		
		const confirmModal = async (content: string, payType:number = 4) => {
			console.log(content);
			if(content) {
				let p = {id: state.goodsId, payType: state.payType === 2 ? payType : state.payType, payPassword: content}
				let res = await paymentDeposit(p)
				console.log(p);
				console.log(res);
				if(res.code === 0) {
					state.page = 1
					state.orderList = []
					orderListFun()
					uni.showToast({ title: '支付成功', icon: 'success' })
					tryCustomeModalNode.value.cancel()
					customeModalNode.value.cancel()
				} else {
					uni.showToast({
						title: res.msg || '支付失败',
						icon: 'none'
					})
				}
			} else {
				uni.showToast({ title: '输入支付密码', icon: 'error' }) 
			} 
		}
		
		return { 
			changeTab,
			orderListFun, 
			reservationHandle,
			selectTime,
			confirm,
			cancel,
			close,
			submitReservation,
			paymentDepositHandle,
			refundMoneyHandle,
			statusText,
			changeType,
			confirmHandle,
			paymentNode,
			reservationInfo,
			confirmModal,
			customeModalNode,
			tryCustomeModalNode,
			tryConfirmModal,
			...toRefs(state)
		}
	}
})
</script>

<style>
	page{ background-color: #f8f8fa;}
</style>

<style lang="scss" scoped>
.order-wrapper{
	padding-bottom: 24rpx;
	.order-list{
		padding: 0 24rpx;
		.order-item{
			background: #ffffff;
			border-radius: 16rpx;
			padding: 20rpx;
			margin-top: 20rpx;
			.store-msg{
				.store-icon{
					width: 32rpx;
					height: 32rpx;
					margin-right: 14rpx;
				}
			}
			.goods-wrapper{
				border-radius: 16rpx;
				overflow: hidden;
				background: #f8f8fa;
				margin-top: 10rpx;
				margin-bottom: 10rpx;
				.goods-item{
					justify-content: flex-start;
					.goods-pic{
						width: 170rpx;
						height: 170rpx;
						margin-right: 10rpx;
					}
					.goods-msg{
						padding: 20rpx;
						flex: 1;
						.goods-top{
							font-size: 26rpx;
							font-weight: 500;
							text-align: LEFT;
							color: #333333;
							line-height: 44rpx;
							display: flex;
							align-items: flex-start;
							justify-content:space-between;
							.goods-title{
								display: flex;
								flex-grow:3;
							}
							.goods-price{
								display: flex;
								flex-direction: column;
								align-items: flex-end;
								flex-grow:1;
							}
						}
					}
				}
			}
			.order-msg{
				justify-content: space-between;
				align-items: flex-end;
				font-size: 26rpx;
				font-family: PingFang SC, PingFang SC-400;
				font-weight: 400;
				color: #999999;
				.price{
					display: flex;
					align-items: baseline;
					color:#333333;
					.priceNum{
						color:#333333;
						font-size: 40rpx;
						display: flex;
						align-items: baseline;
					}
				}
			}
			.order-menu{
				display: flex;
				justify-content: flex-end; 
				.order-status-btn{
					width: 166rpx;
					height: 66rpx; 
					border-radius: 34rpx;
					text-align: center;
					line-height: 66rpx;
				}
				.shouhou{ 
					font-size: 26rpx;
					font-family: PingFang SC, PingFang SC-500;
					font-weight: 500;
					color: #666666;
					margin-left: 15rpx;
				}
				.wuliu{ 
					background: #F8F8FA;
					font-size: 26rpx;
					font-family: PingFang SC, PingFang SC-500;
					font-weight: 500;
					color: #333333;
					margin-left: 15rpx;
				}
				.fukuan{
					background: #f9dee8;
					font-size: 26rpx;
					font-family: PingFang SC, PingFang SC-500;
					font-weight: 500;
					margin-left: 15rpx;
					color: #f33c72;
				}
				.shouhuo{ 
					background: #f9dee8;
					font-size: 26rpx;
					font-family: PingFang SC, PingFang SC-500;
					font-weight: 500;
					margin-left: 15rpx;
					color: #f33c72; 
				}
			}
		}
	}
	.reservation-info-content{
		padding: 24rpx;
		padding-bottom: 60rpx;
		.reservation-form-item{
			padding: 20rpx 0;
			.reservation-form-item-label{
				width: 200rpx;
			}
		}
		.public-large-btn{
			margin-top: 60rpx;
		}
	}
}
</style>